﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

using JetBrains.Annotations;

using WpfApp4.Models;
using WpfApp4.Models.Config;

using XEvent;
using XEvent.Events;

namespace WpfApp4.Utilities
{
    public class WindowManager : Singleton<WindowManager>
    {
        private WindowEvent _windowEvent;
        public IDictionary<string, Window> windowDic = new Dictionary<string, Window>();

        public WindowManager()
        {
            _windowEvent = XEventAgent.Instance.EventManager.GetEvent<WindowEvent>();
        }

        public void Add(string key, Window window)
        {
            windowDic.Add(key, window);
            window.Title = key;

            UpdateMenuConfig(key);

            _windowEvent.Publish(new WindowEvent
            {
                Data = window,
                Type = EventType.Action,
                WindowActionType = WindowActionType.Open,
                EventId = EventId.OpenBrowseWindow,
            });
        }

        public void Remove(Window window)
        {
            windowDic.Remove(window.Title);
            RemoveMenuConfig(window.Title);
        }

        public void Remove(string key)
        {
            windowDic.Remove(key);
            RemoveMenuConfig(key);
        }

        public Window GetWindow(string key)
        {
            return windowDic[key];
        }

        private void UpdateMenuConfig(string key)
        {
            MenuConfig menu = Utility.GetMenuByName("已打开窗口");
            var list = menu.MenuItems?.ToList() ?? new List<MenuConfig>();
            list.Add(new MenuConfig { Name = key, Command = "CloseBrowserWindowCommand" });
            menu.MenuItems = list.ToArray();

            SaveConfig();
        }

        private void RemoveMenuConfig(string key)
        {
            MenuConfig menu = Utility.GetMenuByName("已打开窗口");
            var list = menu.MenuItems?.ToList() ?? new List<MenuConfig>();

            var item = list.Where(m => m.Name == key);
            if (item.Any())
            {
                list.Remove(item.First());
            }

            if (list.Count == 0)
            {
                var mItems = MenuInfo.Instance.MenuItems.ToList();
                var index = mItems.IndexOf(menu);
                mItems.RemoveAt(index);
                MenuInfo.Instance.MenuItems = mItems.ToArray();
            }
            else
            {
                menu.MenuItems = list.ToArray();
            }

            SaveConfig();
        }

        private void SaveConfig()
        {
            ConfigManager.SaveConfig();
            _windowEvent.Publish(new WindowEvent
            {
                Type = EventType.Action,
                WindowActionType = WindowActionType.Update,
                EventId = EventId.RefreshMenu,
            });
        }
    }
}
